package RaceSimulation;

public class RaceSimulation {
    private static final int TOTAL_DISTANCL = 50;
    private static final double RABBIT_SPEED = 5.0;//每秒5米
    private static final double TURTLE_SPEED = 3.0;//每秒3米
    // private static final double REST_TIME = 2.0;//兔子的休息时间，单位秒，兔子完成
    private static final double REST_TIME = 7.0;//兔子的休息时间，单位秒，乌龟完成

    public static void main(String[] args)
    {
        Thread rabbitThread = new Thread(new Runner("Rabbit",RABBIT_SPEED,REST_TIME));
        Thread turtleThread = new Thread(new Runner("Turle",TURTLE_SPEED,0));

        rabbitThread.start();
        turtleThread.start();
    }

    static class Runner implements Runnable{
        private final String name;
        private final double speed;
        private final double restTime;
        private double distanceCovered = 0;

        Runner(String name,double speed,double restTime)
        {
            this.name = name;
            this.speed = speed;
            this.restTime = restTime;
        }

        @Override
        public void run()
        {
            while(distanceCovered<TOTAL_DISTANCL)
            {
                try{
                    Thread.sleep(100);
                    distanceCovered+=speed*0.1;
                    System.out.printf("%s: %.1f meters\n",name,distanceCovered);

                    if(name.equals("Rabbit")&&distanceCovered>=40)
                    {
                        System.out.println(name+" is taking a rest.");
                        Thread.sleep((long)(restTime*1000));//兔子在40米处休息
                    }
                }catch(InterruptedException e)
                {
                    Thread.currentThread().interrupt();
                }
            }
            System.out.println(name+" has finished the race!");
        }
    }
}
